<?php

defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?:'main';
$activity_tables=array(
		'goods'=>'coupon_goodsendtask',
		'order'=>'coupon_sendtasks',
		'new'=>'coupon_sendticket',
		'huodong'=>'coupon_huodongsendtask',
);
if($_RQ['op']=='main'){
	//展示获得的活动卡券
	$id=intval($_RQ['id']);
	$give=$this->pdo_get('coupon_wait',array('id'=>$id));
	if(!$give){
		exi('活动不存在！','error');
	}
	$activity=$this->pdo_get($activity_tables[$give['ac_type']],array('id'=>$give['ac_id']));
	if($activity['couponid']){
		$couponids=str_array($activity['couponid']);
		$coupons=$this->pdo_getall('coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$couponids));
		foreach($coupons as $k=>&$v){	
			$v['coupon']=$this->model('coupon')->intcoupon($v['id']);
			if(!$v['coupon']['id']){
				unset($coupons[$k]);
			}
		}
		$return['coupons']=$coupons;
	}else{
		$return['coupons']=array();
	}
	$give['activity']=$activity;
	$return['item']=$give;
	$return['post']=array('id'=>$give['id']);
	exi($return);
}
if($_RQ['op']=='post'){
	//领取活动获得的卡券
	$post=get_postdata();
	$id=intval($post['id']);
	$give=$this->pdo_get('coupon_wait',array('id'=>$id));
	if(!$give){
		exi('活动不存在！','error');
	}
	if($give['status']==1){
		exi('您已经领取过了！','error');
	}
	$table=$activity_tables[$give['ac_type']];
	$activity=$this->pdo_get($table,array('id'=>$give['ac_id']));
	if(isset($activity['num']) && $activity['num']<$activity['sendnum']){
		exi('卡券已经被领完啦，下次早点哦！','error');
	}
	
	$couponids=str_array($activity['couponid']);
	foreach($couponids as $couponid){
		for($i=0;$i<$activity['sendnum'];$i++){
			$this->model('coupon')->getcoupon($couponid);
		}
	}
	$this->pdo_update('coupon_wait',array('status'=>1),array('id'=>$give['id']));
	if(isset($activity['num']) && $activity['sendnum']){
		$this->pdo_update($table,array('num -='=>$activity['sendnum']),array('id'=>$activity['id']));
	}
	$nowplugin=$_SESSION['current_plugin']?:'jy_weishop';
	exi('优惠券领取成功！','',$nowplugin.'/index/');
}
